package com.bjzsly.star3.xzb.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.webkit.WebSettings;
import android.webkit.WebView;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.List;
import java.util.UUID;

import static android.content.Context.TELEPHONY_SERVICE;

/**
 * Created by Star3 on 2017/4/8.
 */
public class DeviceUtil {

    /**
     * 获取手机 IMEI
     *
     * @param context
     * @return
     */
    public static String getDeviceId(Context context) {
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
            return checkDeviceId(tm.getDeviceId());
        } catch (Exception e) {
            return checkDeviceId(null);
        }
    }

    /**
     * 获取手机 IMSI
     * 判断IMSI可以判断SIM是否存在
     * @param context
     * @return
     */
    public static String getSubscriberId(Context context) {
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
            return tm.getSubscriberId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取设备名称
     *
     * @return
     */
    public static String getModel() {
        return Build.MODEL;
    }

    /**
     * 获取制造商
     *
     * @return
     */
    public static String getManufacturer() {
        return Build.MANUFACTURER;
    }

    /**
     * 获取安卓系统版本号
     *
     * @return
     */
    public static int getAndroidOSVersion() {
        return Build.VERSION.SDK_INT;
    }

    private static String defaultUserAgent;

    private static String getDefaultUserAgent(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            try {
                return WebSettings.getDefaultUserAgent(context);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN) {
            try {
                final Class<?> webSettingsClassicClass = Class.forName("android.webkit.WebSettingsClassic");
                final Class<?> webViewClassicClass = Class.forName("android.webkit.WebViewClassic");
                final Constructor<?> constructor = webSettingsClassicClass.getDeclaredConstructor(Context.class, webViewClassicClass);
                constructor.setAccessible(true);
                final Object object = constructor.newInstance(context, null);
                final Method method = webSettingsClassicClass.getMethod("getUserAgentString");
                return (String) method.invoke(object);
            } catch (final Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                Constructor<WebSettings> constructor = WebSettings.class.getDeclaredConstructor(Context.class, WebView.class);
                constructor.setAccessible(true);
                WebSettings settings = constructor.newInstance(context, null);
                return settings.getUserAgentString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            WebView webView = new WebView(context);
            WebSettings webSettings = webView.getSettings();
            return webSettings.getUserAgentString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return System.getProperty("http.agent");
    }

    /**
     * 获取系统默认UA
     *
     * @param context
     * @return
     */
    public static String getUserAgent(Context context) {
        if (defaultUserAgent == null) {
            synchronized (DeviceUtil.class) {
                if (defaultUserAgent == null) {
                    defaultUserAgent = getDefaultUserAgent(context);
                }
            }
        }
        return defaultUserAgent;
    }

    /**
     * 判断是否为wifi
     *
     * @param context
     * @return
     */
    public static boolean isWifi(Context context) {
        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean isNetConnected(Context ctx) {
        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isAvailable())
                return true;
        } catch (Exception e) {
        }
        return false;
    }

    /**
     * 获取MAC地址
     *
     * @param context
     * @return
     */
    public static String getWifiMacAddress(Context context) {
        try {
            Context app = context.getApplicationContext();
            WifiManager wm = (WifiManager) app.getSystemService(Context.WIFI_SERVICE);
            if (wm.isWifiEnabled()) {
                WifiInfo info = wm.getConnectionInfo();
                return info.getMacAddress();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int getScreenWidth(Context context) {
        final DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return displayMetrics.widthPixels;
    }

    public static int getScreenHeight(Context context) {
        final DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return displayMetrics.heightPixels;
    }

    public static String randomDeviceUUID(Context context) {
        UUID uuid;
        final String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        try {
            if (!"9774d56d682e549c".equals(androidId)) {
                uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
            } else {
                final String deviceId = getDeviceId(context);
                uuid = deviceId != null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            uuid = UUID.randomUUID();
        }
        return uuid.toString();
    }

    /**
     * 获取app版本名
     */
    public static String getAppVersionName(Context context) {
        PackageManager pm = context.getPackageManager();
        PackageInfo pi;
        try {
            pi = pm.getPackageInfo(context.getPackageName(), 0);
            return pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取应用程序版本名称信息
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取app版本号
     */
    public static int getAppVersionCode(Context context) {
        PackageManager pm = context.getPackageManager();
        PackageInfo pi;
        try {
            pi = pm.getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
        }
        return 0;
    }

    public static String getAppChannel(Context ctx, String key) {
        if (ctx == null || TextUtils.isEmpty(key)) {
            return null;
        }
        String resultData = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        resultData = applicationInfo.metaData.getString(key);
                    }
                }

            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return resultData;
    }


    public static String getAppChannel(Context ctx) {
        if (ctx == null) {
            return null;
        }
        String resultData = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        resultData = applicationInfo.metaData.getString(ConstanceValue.META_CHANNEL_VALUE);
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultData;
    }

    public static String getMetaValue(Context ctx, String keyName) {
        if (ctx == null) {
            return null;
        }
        String resultData = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        resultData = applicationInfo.metaData.getString(keyName);
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultData;
    }


    private static final int _1KB = 1024;
    private static final int _1MB = _1KB * _1KB;
    private static final int _1GB = _1KB * _1MB;

    public static String formatFileSize(long size) {
        if (size <= 0) return "0B";
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (size < _1KB)
            fileSizeString = df.format((double) size) + "B";
        else if (size < _1MB)
            fileSizeString = df.format((double) size / _1KB) + "KB";
        else if (size < _1GB)
            fileSizeString = df.format((double) size / _1MB) + "MB";
        else
            fileSizeString = df.format((double) size / _1GB) + "GB";

        return fileSizeString;
    }


//    public static long getWebCacheDir(Context ctx) {
////        File file =new File(ctx.getFilesDir(), "webCache");
////        if(!file.exists()) file.mkdirs();
////        return file.getAbsolutePath();
//        long size = getFolderSize(ctx.getCacheDir());
//
////        size += getFolderSize(ctx.getDatabasePath("webview.db"));
////        size += getFolderSize(ctx.getDatabasePath("webviewCache.db"));
//        Log.e("1234",ctx.getDatabasePath("webview.db").getAbsolutePath());
//        Log.e("1234",ctx.getDatabasePath("webviewCache.db").getAbsolutePath());
//
//        Log.e("1234",ctx.getDatabasePath("webview.db").exists()+"");
//        Log.e("1234",ctx.getDatabasePath("webviewCache.db").exists()+"");
//        Log.e("1234",new WebView(ctx).getSettings().);
//
//
//        return size;
//
//    }
//
//
//    public static long getWebCache(Context ctx){
//
//        long cacheSize = getFolderSize(new File(getWebCacheDir(ctx)));
//        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            cacheSize += getFolderSize(ctx.getExternalCacheDir());
//        }
//        return cacheSize;
//    }


    public static long getFolderSize(File folder) {
        if (folder == null) return 0;
        long size = 0;
        File[] files = folder.listFiles();
//        Log.d("1234", "files -->>" + files.length);
        for (int i = 0; i < files.length; i++) {
//            Log.d("1234", "files -->>" + files[i].getAbsolutePath());


            if (files[i].isDirectory())
                size = size + getFolderSize(files[i]);
            else
                size = size + files[i].length();
        }
        return size;
    }


    public static void createFolder(String path) {
        try {
            File file = new File(path);
            if (!file.exists())
                file.mkdirs();
        } catch (Exception e) {
        }
    }


    public static void deleteFolder(String path) {
        try {
            File file = new File(path);
            if (file.isFile()) {
                file.delete();
                return;
            }
            if (file.isDirectory()) {
                File[] childFile = file.listFiles();
                if (childFile == null || childFile.length == 0) {
                    file.delete();
                    return;
                }
                for (File f : childFile) {
                    deleteFolder(f.getAbsolutePath());
                }
                file.delete();
            }
        } catch (Exception e) {
        }
    }


    public static void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        deleteFolderFile(files[i].getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {
                        file.delete();
                    } else {// 目录
                        if (file.listFiles().length == 0) {
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void deleteFolderFile(Context ctx, String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        deleteFolderFile(files[i].getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {
                        String deletePath = file.getAbsolutePath();
                        file.delete();
                        refreshSysPics(ctx, deletePath);
                    } else {// 目录
                        if (file.listFiles().length == 0) {
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private static void refreshSysPics(Context ctx, String filePath) {
        try {
            ctx.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + filePath)));
        } catch (Exception e) {
        }
    }

    public static boolean isSIMAviable(Context ctx) {
        try {
            TelephonyManager telMgr = (TelephonyManager)
                    ctx.getSystemService(TELEPHONY_SERVICE);
            int simState = telMgr.getSimState();
            boolean result = true;
            switch (simState) {
                case TelephonyManager.SIM_STATE_ABSENT:
                case TelephonyManager.SIM_STATE_UNKNOWN:
                    result = false;
                    break;
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private static String checkDeviceId(String deviceId) {
        if (!TextUtils.isEmpty(deviceId))
            return deviceId;
        try {
            return "35" +
                    Build.BOARD.length() % 10 +
                    Build.BRAND.length() % 10 +
                    Build.CPU_ABI.length() % 10 +
                    Build.DEVICE.length() % 10 +
                    Build.DISPLAY.length() % 10 +
                    Build.HOST.length() % 10 +
                    Build.ID.length() % 10 +
                    Build.MANUFACTURER.length() % 10 +
                    Build.MODEL.length() % 10 +
                    Build.PRODUCT.length() % 10 +
                    Build.TAGS.length() % 10 +
                    Build.TYPE.length() % 10 +
                    Build.USER.length() % 10;
        } catch (Exception e) {
        }
        return null;
    }

    public static String getPropertyInfo() {
        try {
            String proHost = android.net.Proxy.getDefaultHost();
            int proPort = android.net.Proxy.getDefaultPort();
            if (proHost != null && proPort != -1)
                return proHost + ":" + proPort;
        } catch (Exception e) {
        }
        return null;
    }

    public static String getAndroidId(Context context) {
        try {
            return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean isAppInstall(Context context, String packageName) {
        try {
            PackageManager packageManager = context.getPackageManager();
            List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
            if (pinfo != null) {
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
                    if (!TextUtils.isEmpty(pn) && pn.equals(packageName)) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    public static boolean isRunningForeground(Context ctx) {
        ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcessInfos = activityManager.getRunningAppProcesses();
        // 枚举进程
        for (ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessInfos) {
            if (appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                if (appProcessInfo.processName.equals(ctx.getApplicationInfo().processName)) {
                    return true;
                }
            }
        }
        return false;
    }
}
